const StockAdjustment = require("../models/stockAdjustmentModel");
const Warehouse = require("../models/warehouseModel"); 
const Item = require("../models/itemModel"); 

// CREATE Stock Adjustment
exports.createStockAdjustment = async (req, res) => {
  try {
    const { warehouse, adjustmentDate, referenceNo, items, note, createdBy } = req.body;

    if (!warehouse || !adjustmentDate || !items || items.length === 0) {
      return res.status(400).json({ success: false, message: "Missing required fields" });
    }

    
    let totalQuantity = 0;
    items.forEach((i) => {
      totalQuantity += i.quantity;
    });

    const newAdjustment = new StockAdjustment({
      warehouse,
      adjustmentDate,
      referenceNo,
      items,
      totalQuantity,
      note,
      createdBy
    });

    await newAdjustment.save();
    return res.status(201).json({
      success: true,
      message: "Stock adjustment created successfully",
      data: newAdjustment,
    });
  } catch (error) {
    return res.status(500).json({ success: false, message: error.message });
  }
};

// GET All Stock Adjustments
exports.getAllStockAdjustments = async (req, res) => {
  try {
    
    const filter = {};
    if (req.query.warehouse) {
      filter.warehouse = req.query.warehouse;
    }

    const adjustments = await StockAdjustment.find(filter)
      .populate("warehouse", "warehouseName")
      .populate("items.item", "itemName salesPrice");
    return res.status(200).json({ success: true, data: adjustments });
  } catch (error) {
    return res.status(500).json({ success: false, message: error.message });
  }
};

// GET Single Stock Adjustment
exports.getStockAdjustmentById = async (req, res) => {
  try {
    const adjustment = await StockAdjustment.findById(req.params.id)
      .populate("warehouse", "warehouseName")
      .populate("items.item", "itemName salesPrice");
    if (!adjustment) {
      return res.status(404).json({ success: false, message: "Stock adjustment not found" });
    }
    return res.status(200).json({ success: true, data: adjustment });
  } catch (error) {
    return res.status(500).json({ success: false, message: error.message });
  }
};

// UPDATE Stock Adjustment
exports.updateStockAdjustment = async (req, res) => {
  try {
    const { items } = req.body;
    let totalQuantity = 0;
    if (items && items.length > 0) {
      items.forEach((i) => {
        totalQuantity += i.quantity;
      });
      req.body.totalQuantity = totalQuantity;
    }

    const updatedAdjustment = await StockAdjustment.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    )
      .populate("warehouse", "warehouseName")
      .populate("items.item", "itemName salesPrice");

    if (!updatedAdjustment) {
      return res.status(404).json({ success: false, message: "Stock adjustment not found" });
    }

    return res.status(200).json({
      success: true,
      message: "Stock adjustment updated successfully",
      data: updatedAdjustment,
    });
  } catch (error) {
    return res.status(500).json({ success: false, message: error.message });
  }
};

// DELETE Stock Adjustment
exports.deleteStockAdjustment = async (req, res) => {
  try {
    const deletedAdjustment = await StockAdjustment.findByIdAndDelete(req.params.id);
    if (!deletedAdjustment) {
      return res.status(404).json({ success: false, message: "Stock adjustment not found" });
    }
    return res.status(200).json({ success: true, message: "Stock adjustment deleted successfully" });
  } catch (error) {
    return res.status(500).json({ success: false, message: error.message });
  }
};
